connect = require '../../utils/connect'
jquery = require 'jquery'
jsdom = require 'jsdom'
async = require 'async'

crawSingers = ()->
	jsdom.env 'http://ijita.com/singer/', (err, window)->
		$ = jquery.create window

		singers = []
		$('dl').each (i,item)->
			first = item.id
			$('dd a', item).each (j,a)->

				singers.push 
					first:first
					name:a.innerHTML
					source_name:a.href.replace('http://ijita.com/singer/','').replace('.html','')

		async.forEach singers, (singer,callback)->
			sql  = "insert into singers set ?"
			connect.runSql sql, [singer], callback
		,(err)->
			console.log err

crawSingerStave = (singer,callback)->
	url = "http://ijita.com/singer/#{singer.source_name}.html"
	jsdom.env url, (err, window)->
		$ = jquery.create window
		staves = []
		$('tr').each (i,tr)->
			if $('.tformat',tr).html() is '文本谱'
				staves.push
					singer: singer.name
					name: $('a',tr).html()
					i:$('a',tr).attr('href').replace('/tab/','').replace('.html','')
					hot:$('td',tr)[2].innerHTML
		
		async.forEach staves,(stave,callback)->
			console.log stave
			sql = "insert ignore into staves set ?"
			connect.runSql sql, [stave], callback
		,(err)->
			callback err


runSingers = ()->
	sql = "select * from singers where state = 0 order by id desc"
	connect.runSql sql, (err, result)->
		async.forEachSeries result,(singer,callback)->
			crawSingerStave singer, (err)->
				console.log err if err
				sql = "update singers set state = 1 where id = ?"
				connect.runSql sql, [singer.id], callback
		,(err)->
			console.log err if err

crawStave = (i,callback)->
	url = "http://ijita.com/tab/#{i}.html"
	jsdom.env url , (err, window)->
		console.log err if err
		$ = jquery.create window
		content = $('pre').html()
		sql = "update staves set content = ? where i = ?"
		connect.runSql sql, [content, i], callback

runStaves = ()->
	sql = "select * from staves where content = ''"
	connect.runSql sql ,(err, result)->
		console.log err if err
		async.forEachSeries result, (stave, callback)->
			crawStave stave.i, callback
		,(err)->
			console.log err if err

runStaves()